package cn.source.system.service.impl;

import java.util.List;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.source.common.utils.spring.SpringUtils;
import cn.source.system.config.MailConfig;
import cn.source.system.utils.SpringFactoryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.source.system.mapper.DbMailConfigMapper;
import cn.source.system.domain.DbMailConfig;
import cn.source.system.service.IDbMailConfigService;

/**
 * 邮件发送配置Service业务层处理
 *
 * @author sourcebyte.vip
 * @date 2025-03-03
 */
@Service
public class DbMailConfigServiceImpl implements IDbMailConfigService {
    @Autowired
    private DbMailConfigMapper dbMailConfigMapper;

    /**
     * 查询邮件发送配置
     *
     * @param host 邮件发送配置主键
     * @return 邮件发送配置
     */
    @Override
    public DbMailConfig selectDbMailConfigByHost(String host) {
        return dbMailConfigMapper.selectDbMailConfigByHost(host);
    }

    /**
     * 查询邮件发送配置列表
     *
     * @param dbMailConfig 邮件发送配置
     * @return 邮件发送配置
     */
    @Override
    public List<DbMailConfig> selectDbMailConfigList(DbMailConfig dbMailConfig) {
        return dbMailConfigMapper.selectDbMailConfigList(dbMailConfig);
    }

    /**
     * 新增邮件发送配置
     *
     * @param dbMailConfig 邮件发送配置
     * @return 结果
     */
    @Override
    public int insertDbMailConfig(DbMailConfig dbMailConfig) {
        int c = dbMailConfigMapper.insertDbMailConfig(dbMailConfig);
        MailConfig.registerMailConfig(dbMailConfig);
        try {
            MailConfig.sedMail(dbMailConfig.getFrom(), "测试邮件", "测试邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
            throw new RuntimeException("邮件发送配置失败，原因：" + msg);
        }
        //如果这里抛出异常，代表错误
        return c;
    }

    /**
     * 修改邮件发送配置
     *
     * @param dbMailConfig 邮件发送配置
     * @return 结果
     */
    @Override
    public int updateDbMailConfig(DbMailConfig dbMailConfig) {
        return dbMailConfigMapper.updateDbMailConfig(dbMailConfig);
    }

    /**
     * 批量删除邮件发送配置
     *
     * @param hosts 需要删除的邮件发送配置主键
     * @return 结果
     */
    @Override
    public int deleteDbMailConfigByHosts(String[] hosts) {
        return dbMailConfigMapper.deleteDbMailConfigByHosts(hosts);
    }

    /**
     * 删除邮件发送配置信息
     *
     * @param host 邮件发送配置主键
     * @return 结果
     */
    @Override
    public int deleteDbMailConfigByHost(String host) {
        return dbMailConfigMapper.deleteDbMailConfigByHost(host);
    }

    @Override
    public void deleteAll() {
        dbMailConfigMapper.deleteAll();
    }
}
